package com.jzr.bedside.ui.skill

import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andy.ecgviewlib.EcgWaveView
import com.blankj.utilcode.utils.TimeUtils
import com.blankj.utilcode.utils.ToastUtils
import com.google.gson.Gson
import com.inuker.bluetooth.library.Constants
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener
import com.inuker.bluetooth.library.connect.options.BleConnectOptions
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse
import com.inuker.bluetooth.library.connect.response.BleWriteResponse
import com.inuker.bluetooth.library.search.SearchRequest
import com.inuker.bluetooth.library.search.SearchResult
import com.inuker.bluetooth.library.search.response.SearchResponse
import com.jzr.bedside.R
import com.jzr.bedside.base.BaseActivity
import com.jzr.bedside.base.BaseApplication
import com.jzr.bedside.bean.OrderListBean
import com.jzr.bedside.bean.TemperatureBean
import com.jzr.bedside.bean.body.BloodPressureBody
import com.jzr.bedside.bean.body.TemperatureAddBody
import com.jzr.bedside.presenter.contract.BloodPressureActivityContract
import com.jzr.bedside.presenter.contract.TemperatureActivityContract
import com.jzr.bedside.presenter.impl.BloodPressureActivityImpl
import com.jzr.bedside.presenter.impl.TemperatureActivityImpl
import com.jzr.bedside.service.BluetoothChipType
import com.jzr.bedside.service.BluetoothUtils
import com.jzr.bedside.ui.adapter.DeviceAdapter
import com.jzr.bedside.utils.BluetoothUtil
import com.jzr.bedside.utils.Permission
import com.jzr.bedside.utils.PreferUtil
import com.jzr.bedside.view.CustomDialog
import com.medxing.sdk.resolve.BluetoothCMD
import com.medxing.sdk.resolve.NibpResolve
import com.medxing.sdk.resolve.ResolveManager
import com.medxing.sdk.resolve.ResolveManager.OnNibpResolveListener
import com.medxing.sdk.resolve.TypeCastUtil
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.actionbar_root_layout.*
import kotlinx.android.synthetic.main.activity_blood_pressure.*
import kotlinx.android.synthetic.main.activity_temperature.*
import kotlinx.android.synthetic.main.activity_temperature.btnAgainPost
import kotlinx.android.synthetic.main.activity_temperature.btnPost
import kotlinx.android.synthetic.main.activity_temperature.btnStartSean
import kotlinx.android.synthetic.main.activity_temperature.cvTip
import kotlinx.android.synthetic.main.activity_temperature.tvTimer
import okhttp3.MediaType
import okhttp3.RequestBody
import java.util.*

class BloodPressureActivity : BaseActivity(), View.OnClickListener,
    BloodPressureActivityContract.View {

    private val mPresenter = BloodPressureActivityImpl()


    private var diaologDevice: CustomDialog? = null
    private var diaologScan: CustomDialog? = null
    private var diaologAgainScan: CustomDialog? = null
    private var devices = mutableListOf<SearchResult>()

    private var resolveManager: ResolveManager? = null
    private val bluetoothChipType: BluetoothChipType = BluetoothChipType()

    private var bcgWaveView: EcgWaveView? = null
    private var view: View? = null
    private var address: String? = null
    private  var  isShow = false


    override fun getLayoutId(): Int {
        return R.layout.activity_blood_pressure
    }

    override fun attachView() {
        mPresenter.attachView(this)
    }

    override fun detachView() {
        mPresenter.detachView()
    }

    override fun initView() {

        ivRight.setOnClickListener(this)
        btnAgainPost.setOnClickListener(this)
        btnStartSean.setOnClickListener(this)
        btnPost.setOnClickListener(this)

        tvTimer.text = TimeUtils.getNowTimeString()
        resolveManager = ResolveManager.getInstance(this)
        resolveManager?.setOnNibpResolveListener(OnNibpResolveListener { nibpResolve ->
            //                Logger.e("nibpResolve:   >>>>     " + nibpResolve.toString());
            if (nibpResolve.type == NibpResolve.NIBP_TYPE_MEASURE) { //测量中
//                waveBar.setValue(nibpResolve.pressure)
//                tvPressure.withNumber(nibpResolve.pressure).start()
//                butStart.setText("测量中...")
//                Start = true
//                showLoadingDialog("测量中...")
                if(!isShow){
                    showLoadingTest()
                    isShow = true
                }


            }
            if (nibpResolve.type == NibpResolve.NIBP_TYPE_MEASURED) { //测量完成
                hideScanDialog()
                isShow = false
                tvValueDbp.setText(nibpResolve.dbp.toString())
                tvValuePulse.setText(nibpResolve.pulse.toString())
                tvValueSbp.setText(nibpResolve.sbp.toString())
            }
            //id_nibp_test.setText(nibpResolve.toString());
        })


    }

    fun searchDevice() {
        if (!BluetoothUtil.getClient().isBluetoothOpened) {
            BluetoothUtil.getClient().openBluetooth()
        }
        val request = SearchRequest.Builder()
            .searchBluetoothLeDevice(5000, 3)
            .build()
        BluetoothUtil.getClient().search(request, object : SearchResponse {
            override fun onSearchStarted() {

                Permission.requestPermission(this@BloodPressureActivity)
                showDiaologScan()
            }

            override fun onDeviceFounded(device: SearchResult) {
                if (device.name == "MEDXING-NIBP") {
                    if (!devices.contains(device)) {
                        devices.add(device)
                    }
                }
            }

            override fun onSearchStopped() {
                hideScanDialog()
                if (devices.size > 0) {
                    showDeviceDialog(devices)
                } else {
                    showDiaologAgainScan()
                }

            }

            override fun onSearchCanceled() {

            }
        })
    }


    private fun showDiaologScan() {
        hideScanDialog()
        val view = View.inflate(BaseApplication.getContext(), R.layout.dialog_scan, null)
        diaologScan = CustomDialog(this, 300, 250, view, R.style.MyDialog)
        diaologScan?.setCancelable(false)
        diaologScan?.show()
    }

    private fun showLoadingTest() {

        val view =
            View.inflate(BaseApplication.getContext(), R.layout.dialog_loading_test, null)
        diaologScan = CustomDialog(this, 300, 250, view, R.style.MyDialog)
        diaologScan?.setCancelable(false)
        diaologScan?.show()

    }

    /**
     * 再次连接
     */
    private fun showDiaologAgainScan() {
        hideAgainScanDialog()
        val view = View.inflate(BaseApplication.getContext(), R.layout.dialog_again_scan, null)
        val btnAgainScan = view.findViewById<Button>(R.id.btnAgainScan)
        btnAgainScan.setOnClickListener {
            hideAgainScanDialog()
            searchDevice()
        }
        diaologScan = CustomDialog(this, 300, 250, view, R.style.MyDialog)
        diaologScan?.setCancelable(true)
        diaologScan?.show()
    }

    /**
    蓝牙设备列表dialog
     */
    private fun showDeviceDialog(devices: MutableList<SearchResult>?) {

        hideDeviceDialog()
        val view = View.inflate(BaseApplication.getContext(), R.layout.dialog_device_list, null)
        val ivDelete = view.findViewById<ImageView>(R.id.ivDelete)
        val rvDevice = view.findViewById<RecyclerView>(R.id.rvDevice)
        val btnAgSeach = view.findViewById<Button>(R.id.btnAgSeach)

        val adapter = DeviceAdapter(devices)
        rvDevice.adapter = adapter
        val manager = LinearLayoutManager(this)
        rvDevice.layoutManager = manager

        adapter.onListItemClick(object : DeviceAdapter.onListItemClick {
            override fun onListItemClick(item: SearchResult?) {
                hideDeviceDialog()
                connect(item)
            }
        })

        ivDelete.setOnClickListener {
            hideDeviceDialog()
        }
        btnAgSeach.setOnClickListener {
            hideDeviceDialog()
            searchDevice()
        }

        diaologDevice = CustomDialog(this, view, R.style.MyDialog)
        diaologDevice?.setCancelable(false)
        diaologDevice?.show()

    }

    private fun hideDeviceDialog() {
        if (diaologDevice != null && diaologDevice?.isShowing!!) {
            diaologDevice?.dismiss()
            diaologDevice = null
        }
    }

    private fun hideScanDialog() {
        if (diaologScan != null && diaologScan?.isShowing!!) {
            diaologScan?.dismiss()
            diaologScan = null
        }
    }

    private fun hideAgainScanDialog() {
        if (diaologAgainScan != null && diaologAgainScan?.isShowing!!) {
            diaologAgainScan?.dismiss()
            diaologAgainScan = null
        }
    }

    private fun connect(item: SearchResult?) {
        showLoadingDialog("正在连接中....")
        val options = BleConnectOptions.Builder()
            .setConnectRetry(3)
            .setConnectTimeout(1000)
            .setServiceDiscoverRetry(1)
            .setServiceDiscoverTimeout(1000)
            .build()
        BluetoothUtil.getClient().connect(
            item?.address, options
        ) { code, profile ->
            dismissLoadingDialog()
            when (code) {
                Constants.REQUEST_SUCCESS -> {
                    bluetoothChipType.mac = item?.address
                    address = item?.address
                    val chipType = BluetoothUtils.checkChipType(profile)
                    if (chipType > -1) {
                        BluetoothUtils.setBluetoothChipType(bluetoothChipType)
                        startNotify()
                        BluetoothUtil.getClient()
                            .registerConnectStatusListener(item?.address, mConnectStatusListener)
                        ToastUtils.showLongToastSafe("连接成功...")
                        writeCharacter(BluetoothCMD.IRT_BLE_START_ARRAY);
                        cvTip.visibility = View.VISIBLE
                    } else {
                        ToastUtils.showLongToastSafe("连接失败...")
                        showDiaologAgainScan()
                    }
                }
                Constants.REQUEST_FAILED -> {
                    ToastUtils.showLongToastSafe("连接失败...")
                    showDiaologAgainScan()
                }

                Constants.REQUEST_TIMEDOUT -> {
                    ToastUtils.showLongToastSafe("连接超时...")
                    showDiaologAgainScan()
                }
            }
        }
    }

    private fun startNotify() {
        if (bluetoothChipType.isAvailable) {
            BluetoothUtil.getClient().notify(
                bluetoothChipType.mac,
                bluetoothChipType.serviceUUID,
                bluetoothChipType.notificationUUID,
                object :
                    BleNotifyResponse {
                    override fun onNotify(
                        service: UUID,
                        character: UUID,
                        value: ByteArray
                    ) {
                        Logger.e("run: " + TypeCastUtil.bytesToHexString(value));
                        resolveManager?.pushData(*value)
                    }

                    override fun onResponse(code: Int) {}
                })
        } else { //            sendBroadcast(new Intent(BLUETOOTH_DEVICES_NOT_CONNECTED));

        }

    }

    override fun onDestroy() {
        super.onDestroy()
        BluetoothUtil.getClient().unregisterConnectStatusListener(address, mConnectStatusListener)
        BluetoothUtil.getClient().disconnect(address)
    }

    private val mConnectStatusListener: BleConnectStatusListener =
        object : BleConnectStatusListener() {
            override fun onConnectStatusChanged(mac: String, status: Int) {
                val mConnected = status == Constants.STATUS_CONNECTED
                if (!mConnected) {
                    showDiaologAgainScan()
                }
            }
        }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ivRight -> {
                finish()
            }
            R.id.btnAgainPost -> {
                writeCharacter(BluetoothCMD.IRT_BLE_START_ARRAY)
            }
            R.id.btnStartSean -> {
                searchDevice()
            }
            R.id.btnPost -> {
                if (tvValueSbp.text.toString() != "" && tvValuePulse.text.toString() != "" && tvValueDbp.text.toString() != "") {
                    val dataList = mutableListOf<BloodPressureBody>()
                    val body = BloodPressureBody()
                    body.patientId = PreferUtil.getInstance().patientId!!
                    body.bedNo = PreferUtil.getInstance().bedCode
                    body.admissionId = PreferUtil.getInstance().cureNo
                    body.createTime = TimeUtils.getNowTimeString()
                    body.sbp = tvValueSbp.text.toString().toDouble()
                    body.pulse = tvValuePulse.text.toString().toDouble()
                    body.dbp = tvValueDbp.text.toString().toDouble()
                    dataList.add(body)
                    val bodys: RequestBody =
                        RequestBody.create(
                            MediaType.parse("application/json; charset=utf-8"),
                            Gson().toJson(dataList)
                        )
                    mPresenter.getBloodPressAdd(this, bodys)
                } else {
                    ToastUtils.showShortToastSafe("请输入血压值")
                }
            }
        }
    }

    fun writeCharacter(cmd: ByteArray?) {
        if (bluetoothChipType.isAvailable) BluetoothUtil.getClient().write(
            bluetoothChipType.mac,
            bluetoothChipType.serviceUUID,
            bluetoothChipType.writeUUID,
            cmd,
            BleWriteResponse { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    Logger.e(
                        "run: " + "数据写入成功" + TypeCastUtil.bytesToHexString(
                            cmd
                        )
                    )
                }
            }) else {
            //            sendBroadcast(new Intent(BLUETOOTH_DEVICES_NOT_CONNECTED));
        }
    }

    override fun getBloodPressAddSuccess(data: TemperatureBean?) {
        ToastUtils.showShortToastSafe(data?.message)
        finish()
    }

    override fun showError(message: String?) {
        ToastUtils.showShortToastSafe(message)
    }

}
